import cv2 as cv
import cv2
import os
import numpy as np
import test
from scipy import ndimage
import numpy
import numpy as np
import Home
import math
np.set_printoptions(threshold=np.inf)



#step 1：判断横坐标数字位置，确定数字大小，最后确定边框的上中右
def local_number_down(image):
    image_gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)

    # region Step 1 先找到纵坐标数字的那一列
    # start, end = 0, 0  # 左边一列的数字
    down ,up= 0,0  # 下面的数字底部位置
    number_top,number_down=0,0#底部数字的上下边
    jamb_up,jamb_down,jamb_left,jamb_right=0,0,0,0
    left_number_end=0
    left_number_start=0
    number_high=0

#画竖线
    histogram_row = np.sum(image_gray[:,image_gray.shape[0]//2:], axis=1)  # 每一行相加
    for i in range(10,image.shape[0]-10):
        if abs(histogram_row[i] -histogram_row[i+1])>255:
            jamb_up,up = i,i
            break
    for i in range(image.shape[0]-10,10,-1):
        if abs(histogram_row[i] -histogram_row[i-1])>255:
            down = i-1
            number_down=down
            #计算数字高度
            for j in  range(i-1,10,-1):
                if histogram_row[j]==histogram_row[i+1]:
                    number_top=j
                    break
            break
# 画横线
    histogram = np.sum(image_gray, axis=0)  # 每一列相加
    for i in range(10, len(histogram)-10):
        if abs(histogram[i] -histogram[i+1])>255:
            left_number_start = i
            break
    for i in range(len(histogram)-10,10,-1):
        if abs(histogram[i] -histogram[i+1])>255:
            jamb_right= i
            break



#找到横坐标数字0
    zero_start,zero_end=0,0
    for i in range(10,image.shape[1]-10):
        if image_gray[down,i]>image_gray[10,10]:
            zero_start=i
            for j in range(i,i+20):
                if image_gray[down,j]==image_gray[10,10]:
                    zero_end=j-1
                    break
            break

#找到左边一列数字
    histogram = np.sum(image_gray, axis=0)  # 每一列相加

    for i in range(zero_start, 10, -1):
        if histogram[i] > histogram[zero_start]*1.5:
            left_number_end=i-1
            break


    jamb_left=zero_mid=(zero_end+zero_start)//2
    number_high=abs(number_top-number_down)
    jamb_down=number_top


    image[down, :, :] = 255
    image[up, :, :] = 255
    image[number_top, :, :] = 255
    image[number_down, :, :] = 255
    image[:, left_number_start, :] = 255
    image[:, left_number_end, :] = 255
    image[:, jamb_right, :] = 255
    image[:, zero_mid, :] = 255
    image[:, zero_start, :] = 120
    image[:, zero_end, :] = 120


    cv.imshow("fen_ge_qu_xan.bu.fen"+Home.Image_name, image)
   #返回    图片划线，左边数字开始位置，       右边竖线位置，               左边竖线位置， 下边数字下方位置，上面位置， 数字高度
    return image,   left_number_start,        left_number_end,        zero_mid,   down,         up,    number_high,jamb_up,jamb_down,jamb_left,jamb_right

def  split_numbers(image,left_number_start,left_number_end,number_high):
    print("numberhigh",number_high)
    numbers=[]

    # 画竖线
    up=0
    down=0
    histogram_row = np.sum(image[:, left_number_start:left_number_end+2], axis=1)  # 每一行相加
    for i in range(10, image.shape[0] - 10):
        if all(histogram_row[i] !=histogram_row[10]):
            if up==0:
                up=i

        else:
            if up!=0 and i-up>number_high*0.75:

                down=i


                histogram_number=np.sum(image[up:down, left_number_start-20:left_number_end+2,:], axis=0)
                for j in range(5,len(histogram_number)):
                    if any(histogram_number[j] !=histogram_number[0]):
                        start=j+left_number_start-21
                        break
                number=[(down+up)//2,start]
                numbers.append(number)


                image[up, start:left_number_end+2, :] = 255
                image[down, start:left_number_end+2, :] = 255
                image[up:down, start, :] = 255
                image[up:down, left_number_end+2, :] = 255
                image[(down+up)//2,:,:]=255#数字中线
                up = 0


    # for i in range(image.shape[0] - 10, 10, -1):
    #     if abs(histogram_row[i] - histogram_row[i - 1]) > 255:
    #         down = i - 1
    #         # 计算数字高度
    #         for j in range(i - 1, 10, -1):
    #             if histogram_row[j] == histogram_row[i + 1]:
    #                 number_top = j
    #                 break
    #         break

    cv.imshow("numbers",image)
    #返回number列表，每个number【中值，开始位置】
    return numbers



def ColourDistance(rgb_1, rgb_2):
    R_1, G_1, B_1 = rgb_1
    R_2, G_2, B_2 = rgb_2
    rmean = (R_1 + R_2) / 2
    R = R_1 - R_2
    G = G_1 - G_2
    B = B_1 - B_2
    return math.sqrt((2 + rmean / 256) * (R ** 2) + 4 * (G ** 2) + (2 + (255 - rmean) / 256) * (B ** 2))



#step 2:把边框中的值进行相减，获得弱图像
def colour_sub(image,jamb_up,jamb_down,jamb_left,jamb_right):
    #去除多余部分
    image[:jamb_up,:,:]=0
    image[jamb_down:,:,:]=0
    image[:,jamb_right:,:]=0
    image[:,:jamb_left,:]=0

    image_origal=image.copy()
    image_sub = image[:, :, 0]
    for j in range(4, image.shape[1] - 4):
        for i in range(4, image.shape[0] - 4):
            #2*2
            if all(image[i, j] == image[i, j + 1]) and all(image[i, j] == image[i + 1, j]) and all(
                    image[i, j] == image[i + 1, j + 1]) :
                image_sub[i, j] = image_sub[i, j + 1] = image[i + 1, j + 1] = image[i + 1, j] = 0
            #4*1
            if all(image[i,j]==image[i,j+1])and all(image[i,j]==image[i,j+2])and all(image[i,j]==image[i,j+3]):
                image_sub[i, j] = image_sub[i, j + 1] = image[i, j + 2] = image[i , j+3] = 0
            if all(image[i,j]==image[i+1,j])and all(image[i,j]==image[i+2,j])and all(image[i,j]==image[i+3,j]):
                image_sub[i, j] = image_sub[i+1, j ] = image[i+2, j] = image[i +3, j] = 0
    for j in range(1, image.shape[1] - 1):
        for i in range(1, image.shape[0] - 1):
            if image_sub[i, j] == 0:
                image[i, j, :] = 0


    # 去除白色小点点
    # 腐蚀或膨胀
    kernel1 = cv.getStructuringElement(cv.MORPH_RECT, (1, 5))  # 定义一个10x10的矩形核
    kernel2 = cv.getStructuringElement(cv.MORPH_RECT, (1, 5))  # 定义一个10x10的矩形核
    kernel3 = cv.getStructuringElement(cv.MORPH_RECT, (2, 5))  # 定义一个10x10的矩形核
    kernel4 = cv.getStructuringElement(cv.MORPH_RECT, (5, 10))  # 定义一个10x10的矩形核
    erode = cv.erode(image, kernel1, 1)  # 削去白色  （图片，区域，次数）
    dilate = cv.dilate(erode, kernel2, 2)  # 增加白色
    # dilate = cv.dilate(dilate, kernel3, 1)  # 增加白色
    # dilate2 = cv.dilate(dilate, kernel4, 1)  # 增加白色
    #
    #
    #

    # cv.imshow("image_sub", image)
    # cv.imshow("erode", erode)
    # cv.imshow("dilate", dilate)
    # cv.imshow("dilate2", dilate)
    # huabu=image_origal.copy()
    # huabu[:,:,:]=0
    #
    #
    # result=cv.bitwise_and(image_origal,huabu,dilate2)
    # cv.imshow("result", result)
    # g = result[:, :, 1]
    # r = result[:, :, 0]
    # b = result[:, :, 2]
    # level = 250
    # color_one = result[:, :, 1]
    # while True:
    #     ret, gg = cv2.threshold(g, level, 255, cv2.THRESH_BINARY_INV)
    #     ret, rr = cv2.threshold(r, level, 255, cv2.THRESH_BINARY_INV)
    #     ret, bb = cv2.threshold(b, level, 255, cv2.THRESH_BINARY_INV)
    #     # print(gg,gg.shape)
    #     # print(np.sum(gg).shape)
    #     gg_sum = np.sum((np.sum(gg))) // 255
    #     rr_sum = np.sum((np.sum(rr))) // 255
    #     bb_sum = np.sum((np.sum(bb))) // 255
    #
    #     level = level - 25
    #     if gg_sum < image.shape[0] * image.shape[1] - 1000 or rr_sum < image.shape[0] * image.shape[
    #         1] - 1000 or bb_sum < image.shape[0] * image.shape[1] - 1000:
    #         print(gg_sum, rr_sum, bb_sum)
    #         if gg_sum <= rr_sum and gg_sum <= bb_sum:
    #             color_one = gg
    #         elif bb_sum <= rr_sum and bb_sum <= gg_sum:
    #             color_one = bb
    #         else:
    #             color_one = rr
    #         break
    #
    # cv2.imshow("color_one", color_one)
    # cv2.imshow("r", rr)
    # cv2.imshow("g", gg)
    # cv2.imshow("b", bb)
    #
    # # 反色把黑线换成白线做掩码
    # color_one_vease = cv2.bitwise_not(color_one)
    # cv2.imshow("color_one_vease", color_one_vease)
    # # 一列一列,从左向右，从上到下如果左边有，先判断上面判断右边
    #
    # # 距离平均大，但是有缓冲，距离缓冲小
    # likeness = 50
    #
    # average = [0, 0, 0]
    # average_count = 0
    #
    # # cv2.imshow("result_img" + str(average_count), color_one_vease)
    # # cv2.waitKey(0)
    # flag = True
    # abc = True
    # for j in range(image.shape[1]):
    #     for i in range(image.shape[0]):
    #         if color_one_vease[i][j] > 0:
    #             average = average + image[i, j]
    #             average_count = average_count + 1
    # average = average // average_count
    # for j in range(image.shape[1]):
    #     for i in range(image.shape[0]):
    #         if ColourDistance(average, image[i, j]) > likeness:
    #             image[i, j, :] = 0
    #
    #
    #
    # return image

    cv.imshow("colour_sub",dilate)
    return dilate


#step 3:获得强图像

def get_augment(image_black,image_sub):
    image_origal=image_black.copy()
    image=image_black.copy()

    # 去除白色小点点
    # 腐蚀或膨胀
    kernel3 = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 定义一个10x10的矩形核
    kernel4 = cv.getStructuringElement(cv.MORPH_RECT, (5, 10))  # 定义一个10x10的矩形核
    dilate1 = cv.dilate(image_sub, kernel3, 3)  # 增加白色
    dilate2 = cv.dilate(dilate1, kernel3, 1)  # 增加白色

    #新建画布，把曲线附近复制上去
    canvas = image_origal.copy()
    canvas[:, :, :] = 0

    ret,mask=cv.threshold(cv.cvtColor(dilate2,cv.COLOR_BGR2GRAY),10,255,cv.THRESH_BINARY)
    result=cv2.bitwise_and(image_origal,image_origal,mask)
    result=image_origal.copy()

    for i in range(mask.shape[0]-1):
        for j in range (mask.shape[1]-1):
            if mask[i,j]==0:
                result[i,j,:]=0


    cv.imshow("result2", result)
    g = result[:, :, 1]
    r = result[:, :, 0]
    b = result[:, :, 2]
    level = 250
    color_one = result[:, :, 1]
    while True:
        ret, gg = cv2.threshold(g, level, 255, cv2.THRESH_BINARY_INV)
        ret, rr = cv2.threshold(r, level, 255, cv2.THRESH_BINARY_INV)
        ret, bb = cv2.threshold(b, level, 255, cv2.THRESH_BINARY_INV)
        # print(gg,gg.shape)
        # print(np.sum(gg).shape)
        gg_sum = np.sum((np.sum(gg))) // 255
        rr_sum = np.sum((np.sum(rr))) // 255
        bb_sum = np.sum((np.sum(bb))) // 255

        level = level - 25
        if gg_sum < image.shape[0] * image.shape[1] - 1000 or rr_sum < image.shape[0] * image.shape[
            1] - 1000 or bb_sum < image.shape[0] * image.shape[1] - 1000:
            print(gg_sum, rr_sum, bb_sum)
            if gg_sum <= rr_sum and gg_sum <= bb_sum:
                color_one = gg
            elif bb_sum <= rr_sum and bb_sum <= gg_sum:
                color_one = bb
            else:
                color_one = rr
            break


    # cv2.imshow("color_one", color_one)
    # cv2.imshow("r", rr)
    # cv2.imshow("g", gg)
    # cv2.imshow("b", bb)

    # 反色把黑线换成白线做掩码
    color_one_vease = cv2.bitwise_not(color_one)
    cv2.imshow("color_one_vease", color_one_vease)
    # 一列一列,从左向右，从上到下如果左边有，先判断上面判断右边

    # 距离平均大，但是有缓冲，距离缓冲小
    likeness = 50
    average = [0, 0, 0]
    average_count = 0

    # cv2.imshow("result_img" + str(average_count), color_one_vease)
    # cv2.waitKey(0)
    flag = True
    abc = True
    for j in range(image.shape[1]):
        for i in range(image.shape[0]):
            if color_one_vease[i][j] > 0:
                average = average + image[i, j]
                average_count = average_count + 1
    average = average // average_count
    for j in range(image.shape[1]):
        for i in range(image.shape[0]):
            if ColourDistance(average, image[i, j]) > likeness:
                image[i, j, :] = 0
    cv.imshow("likeness",image)
#       返回相似像素和增强图片
    return image,color_one_vease





#上下相减+左右相减

def sub_all(image,jamb_up,jamb_down,jamb_left,jamb_right):
    # image = cv2.resize(image, None, fx=2, fy=1, interpolation=cv2.INTER_LINEAR)
    wide=image.shape[1]
    high=image.shape[0]
    # 去除多余部分
    image[:jamb_up, :, :] = 0
    image[jamb_down:, :, :] = 0
    image[:, jamb_right:, :] = 0
    image[:, :jamb_left, :] = 0

    # 上下相减
    image_up_down=image.copy()
    image_down_up=image.copy()
    image_left_right=image.copy()
    image_right_left=image.copy()
    for i in range(1,high - 2):
        image_up_down[i] = image_up_down[i] - image_up_down[i + 1]

    for i in range(1,high - 2):
        image_down_up[i] = image_down_up[i] - image_down_up[i + 1]



    for i in range(wide - 2,1,-1):
        image_left_right[:,i] = image_left_right[:,i] - image_left_right[:,i - 1]
    for i in range(wide - 2,1,-1):
        image_right_left[:,i] = image_right_left[:,i] - image_right_left[:,i - 1]


    image=cv.add(image_up_down,image_down_up)

    # image=cv.add(cv.add(image_left_right,image_up_down),cv.add(image_down_up,image_right_left))

    cv.imshow("image_left_right",image_left_right)
    cv.imshow("image_down_up",image_down_up)
    cv.imshow("image_right_left",image_right_left)
    cv.imshow("image_up_down",image_up_down)
    cv.imshow("image",image)
    kernel_row = cv.getStructuringElement(cv.MORPH_RECT, (1, 2))  # 定义一个1x10的矩形核   一行
    kernel_col = cv.getStructuringElement(cv.MORPH_RECT, (3, 1))  # 定义一个10x1的矩形核  一列
    dilate_col = cv.dilate(image, kernel_col, 1)  # 增加白色
    dilate_row = cv.dilate(image, kernel_row, 1)  # 增加白色
    dilate_image=cv.add(dilate_col,dilate_row)
    cv.imshow("dilate_image", dilate_image)





    #虚线的话，先变成实线，对每个像素点进行上下渲染
    #然后大于80%的全部变黑
    image_gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,image_bin=cv.threshold(image_gray,1,255,cv.THRESH_BINARY)

    histogram_col = np.sum(image_bin, axis=0)
    histogram_row = np.sum(image_bin, axis=1)
    #检测白竖线
    for i in range(1,wide-5):
        if histogram_col[i]>(jamb_down-jamb_up)*255*0.8:
            image_bin[:,i]=image_bin[:,i-1]
    for i in range(1,high-1):
        if histogram_row[i]>(jamb_right-jamb_left)*255*0.8:
            image_bin[i,:]=image_bin[i-1,:]
    cv.imshow("image_bin", image_bin)
    write_path="D:\Shanmh\DeskTop\ Abc"+"\\"+Home.Image_name+".jpg"
    #cv.imwrite(write_path,image_bin)
    print(write_path)
    return image_bin



#方案一
#用3*3小方块一个一个测试，满足折线测试范围
#循环检验
def rotate_test():



    return 0



#方案二、
#运用内外色差运算


#方案三
#运用质心运算
def zhi_xin(image):
    wide=image.shape[1]
    high=image.shape[0]
    image_zhi=image.copy()
    image_zhi[:,:]=0
    for col in range(image.shape[1]-1):
        mid=ndimage.measurements.center_of_mass(image[:,col-1:col+1])
        if not math.isnan(mid[0]):
            mid_int=int(mid[0])
            #质点上方
            image[0:mid_int - high // 5 if 0 < mid_int - high // 5 else 0, col]=0
            # #质点下方
            image[high-1 if high-1 < mid_int + high // 5 else mid_int + high // 5:high-1, col]=0
    cv.imshow("zhi_xin_1", image)

    for col in range(image.shape[1]-1):
        mid=ndimage.measurements.center_of_mass(image[:,col])
        if not math.isnan(mid[0]):
            mid_int = int(mid[0])
            # image[mid_int:,col]=128
            # image_zhi[mid_int,col]=255

    cv.imshow("zhi_xin_2",image)
    cv.imshow("image_zhi",image_zhi)
    return image


#方案四
#以两个质点为对角线，检测上面的颜色，全部相似才可以






def result(image_zhi,numbers,path,jamb_left,jamb_right):

    with open(path, 'r') as f:
        list = f.readlines()
    max = list[0]
    max=int(max)
    number_list = list[1].split(",")
    number_list_f=[]

    image_zhis=[]
    for i in number_list:
        number_list_f.append(float(i))



    for i in range(image_zhi.shape[1]):
        for j in range (image_zhi.shape[0]):
            if image_zhi[j,i]==255 or j==image_zhi.shape[0]-1:
                image_zhis.append(j)
                break

    mid=len(image_zhis)//2
    for i in range(3,mid):
        if image_zhis[mid+i]==image_zhi.shape[0]-1:
            image_zhis[mid+i]=image_zhis[mid+i-1]
        if image_zhis[mid-i]==image_zhi.shape[0]-1:
            image_zhis[mid-i]=image_zhis[mid-i+1]


    # print(image_zhis,len(image_zhis))
    step=(jamb_right-jamb_left)//4
    one,two,three,fore,five=jamb_left+2,jamb_left+step,jamb_left+step*2,jamb_right-step,jamb_right


    index=[]
    print(numbers[-1][0])
    k=max/(numbers[-1][0]-numbers[0][0])
    b=k*numbers[-1][0]
    for i in range(image_zhi.shape[0]):
        index.append(b-k*i)
    print(one,two,three,fore,five)
    print(image_zhis[one], image_zhis[two], image_zhis[three], image_zhis[fore], image_zhis[five])
    print(index[image_zhis[one]],index[image_zhis[two]],index[image_zhis[three]],index[image_zhis[fore]],index[image_zhis[five]])
    print(number_list_f)
    cv.imshow("result",image_zhi)


